package com.dsp.week07.service;

import com.dsp.week07.aop.DataBaseType;
import com.dsp.week07.aop.DataSourceSelect;
import com.dsp.week07.model.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.PreparedStatement;
import java.util.List;

@Service
public class UserService {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @DataSourceSelect(value = DataBaseType.Secondary)
    public List<User> list() {
        String sql = "select id,username,password from user";
        return jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(User.class));
    }

    @DataSourceSelect
    public Long addUser(User user) {
        String sql = "INSERT INTO user (username, password) VALUES (?, ?);";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(connection -> {
            PreparedStatement preparedStatement = connection.prepareStatement(sql,new String[]{"id"});
            preparedStatement.setString(1, user.getUsername());
            preparedStatement.setString(2, user.getPassword());
            return preparedStatement;
        },keyHolder) ;
        return keyHolder.getKey().longValue();
    }
}
